# coding:utf-8
from typing import Dict

from fastapi import Query

from app.models.system import SystemPost
from app.admin.schemas.system import PostBase, PostUpdate


class SystemPostService:
    # 列表
    async def page_list(self, query: Query, page: int = 1, limit: int = 10):
        start = (page - 1) * limit
        count = await SystemPost.filter(is_deleted=False).filter(query).count()
        lists = await SystemPost.filter(is_deleted=False).filter(query).offset(start).limit(limit).all()
        return count, lists

    async def get_id(self, user_id: int):
        result = await SystemPost.get_or_none(id=user_id)
        return result

    async def find(self, query: Query):
        result = await SystemPost.get_or_none(query)
        return result

    async def create(self, obj_in: PostBase):
        if isinstance(obj_in, Dict):
            obj_dict = obj_in
        else:
            obj_dict = obj_in.model_dump()
        if obj_dict['remark'] is None:
            obj_dict['remark'] = ""
        result = await SystemPost.create(**obj_dict)
        return result

    async def update(self, obj_in: PostUpdate):
        if isinstance(obj_in, Dict):
            obj_dict = obj_in
        else:
            obj_dict = obj_in.model_dump()
        if obj_dict['remark'] is None:
            obj_dict['remark'] = ""
        # 删除键
        item_id = obj_dict.pop('id')
        result = await SystemPost.filter(id=item_id).update(**obj_dict)
        return result

    async def remove(self, item_id: int):
        item = await SystemPost.filter(id=item_id).first()
        if item:
            item.is_deleted = True
            await item.save()
            return True
        else:
            return False
